var createError = require('http-errors');
var express = require('express');
var path = require('path');
var logger = require('morgan');
let multer  = require('multer');


var app = express();//创建服务器

//资源托管 
app.use(express.static(path.join(__dirname, './public/template')));
app.use('/admin',express.static(path.join(__dirname, './public/admin')));
app.use(express.static(path.join(__dirname, './public')));

// 安装中间件
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//上传文件分发
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if(req.url.includes('user') || req.url.includes('reg')){
      cb(null, path.join(__dirname,'public','upload','user'))
    }else if(req.url.includes('banner')){
      cb(null, path.join(__dirname,'public','upload','banner'))
    }else{
      cb(null, path.join(__dirname,'public','upload','news'))
    }
  }
})
let upload = multer({ storage })
// let objMulter = multer({ dest: './public/upload' }); //dest: 指定 保存位置（存到服务器)
app.use(upload.any());  //允许上传什么类型文件,any|text|image 代表任何类型 




//响应

//管理端
app.use('/admin/banner',require('./routes/admin/banner'))

//客户端
app.all('/api/*',require('./routes/api/params'))
app.use('/api/news',require('./routes/api/news'))
app.use('/api/reg',require('./routes/api/reg'))
app.use('/api/login',require('./routes/api/login'))
app.use('/api/user',require('./routes/api/user'))

app.use('/api/tel',require('./routes/api/send-code'))

//代理端


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // 客户端接口不存在返回json，管理端接口不存在，返回ejs的渲染
  if(req.url.includes('/api')){
    res.send({err:1,msg:'不存在的接口'})
  }else if(req.url.includes('/admin')){
    res.status(err.status || 500);
    res.render('error');
  }
  
});

module.exports = app;
